<template>
  <div class="home">
    <!-- 顶部导航栏 -->
    <div class="top-nav">
      <div class="nav-left">
        <div class="logo">
          <span class="logo-icon">⚡</span>
          <span class="logo-text">趣享生活</span>
        </div>
      </div>
      
      <div class="nav-center">
        <div class="nav-tabs">
          <button 
            v-for="tab in navTabs" 
            :key="tab.key"
            :class="['nav-tab', { 'active': activeTab === tab.key }]"
            @click="switchTab(tab.key)"
          >
            {{ tab.label }}
          </button>
        </div>
      </div>
      
      <div class="nav-right">
        <button class="search-btn" @click="showSearch = true">
          <svg class="search-icon" width="20" height="20" viewBox="0 0 24 24" fill="none">
            <circle cx="11" cy="11" r="8" stroke="#1890ff" stroke-width="1.5"/>
            <path d="M21 21L16.5 16.5" stroke="#1890ff" stroke-width="1.5" stroke-linecap="round"/>
          </svg>
        </button>
      </div>
    </div>

    <!-- 分类标签栏 -->
    <div class="category-bar">
      <div class="category-scroll">
        <button 
          v-for="channel in myChannels" 
          :key="channel.id"
          :class="['category-tag', { 'active': activeChannel && activeChannel.id === channel.id }]"
          @click="switchChannel(channel)"
        >
          {{ channel.name }}
        </button>
        <button class="category-manage" @click="showChannelManager = true">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
            <circle cx="12" cy="12" r="2" fill="currentColor"/>
            <circle cx="12" cy="5" r="2" fill="currentColor"/>
            <circle cx="12" cy="19" r="2" fill="currentColor"/>
          </svg>
        </button>
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="content-area">
      <!-- 推荐内容流 -->
      <div v-if="activeTab === 'recommend'" class="recommend-content">
        <!-- 空状态：暂无内容 -->
        <div v-if="!loading && recommendations.length === 0" class="empty-content">
          <div class="empty-text">暂无内容</div>
        </div>
        <!-- 内容网格 -->
        <div v-if="recommendations.length > 0" class="content-grid">
          <ContentCard
            v-for="content in recommendations"
            :key="content.content_id"
            :content="content"
            @view="handleContentView"
            @like="handleContentLike"
            @share="handleContentShare"
          />
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container">
          <div class="loading-spinner"></div>
        </div>
      </div>

      <!-- 关注内容 -->
      <div v-else-if="activeTab === 'follow'" class="follow-content">
        <div class="empty-state">
          <div class="empty-icon">👥</div>
          <h3>关注功能开发中</h3>
          <p>敬请期待更多精彩功能</p>
        </div>
      </div>

      <!-- 本地内容 -->
      <div v-else-if="activeTab === 'local'" class="local-content">
        <div class="empty-state">
          <div class="empty-icon">📍</div>
          <h3>本地内容功能开发中</h3>
          <p>敬请期待更多精彩功能</p>
        </div>
      </div>
    </div>

    <!-- 底部导航栏 -->
    <div class="bottom-nav">
      <button 
        v-for="item in bottomNavItems" 
        :key="item.key"
        :class="['nav-item', { 'active': activeBottomTab === item.key }, { 'special': item.special }]"
        @click="switchBottomTab(item.key)"
      >
        <span class="nav-icon">{{ item.icon }}</span>
        <span class="nav-label">{{ item.label }}</span>
        <span v-if="item.badge" class="nav-badge">{{ item.badge }}</span>
      </button>
    </div>

    <!-- 搜索弹窗 -->
    <div v-if="showSearch" class="search-modal" @click="showSearch = false">
      <div class="search-content" @click.stop>
        <div class="search-header">
          <input 
            v-model="searchQuery" 
            type="text" 
            placeholder="搜索内容、用户、话题..."
            class="search-input"
            @keyup.enter="handleSearch"
          />
          <button @click="showSearch = false" class="close-btn">✕</button>
        </div>
        <div class="search-suggestions">
          <p>搜索功能开发中...</p>
        </div>
      </div>
    </div>

    <!-- 频道管理弹窗 -->
    <ChannelManager 
      v-model:show="showChannelManager"
      :activeChannelId="activeChannel ? activeChannel.id : null"
      @channelChange="handleChannelChange"
      @close="loadMyChannels"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { useRouter } from 'vue-router'
import ContentCard from '../components/ContentCard.vue'
import ChannelManager from '../components/ChannelManager.vue'
import { recommendationAPI, userAPI, tagAPI } from '../api'

const router = useRouter()

// 响应式数据
const user = ref({})
const userTags = ref([])
const recommendations = ref([])
const loading = ref(false)
const loadingMore = ref(false)
const hasMore = ref(true)
const currentPage = ref(1)
const pageSize = ref(12)  // 每页显示12条，避免过多内容导致显示不全

// 导航相关
const activeTab = ref('recommend')
const activeBottomTab = ref('home')
const showSearch = ref(false)
const searchQuery = ref('')
const showChannelManager = ref(false)

// 导航标签
const navTabs = ref([
  { key: 'follow', label: '关注' },
  { key: 'recommend', label: '发现' },
  { key: 'local', label: '杭州' }
])

// 频道相关
const myChannels = ref([])  // 用户的频道列表
const activeChannel = ref(null)  // 当前激活的频道

// 加载用户频道
const loadMyChannels = async () => {
  try {
    // 先从localStorage获取
    const localChannels = localStorage.getItem('myChannels')
    let channelIds = []
    
    if (localChannels) {
      channelIds = JSON.parse(localChannels)
    } else {
      // 从后端获取
      const response = await userAPI.getUserTags()
      if (response.data.code === 0 && response.data.data) {
        channelIds = response.data.data.map(tag => tag.id)
      }
    }
    
    // 如果没有频道，设置默认频道
    if (channelIds.length === 0) {
      channelIds = [1] // 默认推荐频道
      localStorage.setItem('myChannels', JSON.stringify(channelIds))
    }
    
    // 获取频道详情
    const allTagsResponse = await tagAPI.getTags()
    if (allTagsResponse.data.code === 0) {
      const allTags = allTagsResponse.data.data
      myChannels.value = allTags.filter(tag => channelIds.includes(tag.id))
      
      // 设置默认激活频道
      if (!activeChannel.value && myChannels.value.length > 0) {
        activeChannel.value = myChannels.value[0]
      }
    }
  } catch (error) {
    console.error('加载频道失败:', error)
    // 设置默认频道
    myChannels.value = [{ id: 1, name: '推荐', icon: '📌' }]
    activeChannel.value = myChannels.value[0]
  }
}

// 切换频道
const switchChannel = (channel) => {
  activeChannel.value = channel
  // 重新加载内容
  recommendations.value = []
  currentPage.value = 1
  hasMore.value = true
  loadRecommendations()
}

// 处理频道变化（从频道管理器）
const handleChannelChange = (channel) => {
  switchChannel(channel)
}

// 底部导航
const bottomNavItems = ref([
  { key: 'home', label: '首页', icon: '🏠', special: false },
  { key: 'shopping', label: '购物', icon: '🛒', special: false },
  { key: 'publish', label: '发布', icon: '➕', special: true },
  { key: 'message', label: '消息', icon: '💬', badge: '3', special: false },
  { key: 'profile', label: '我的', icon: '👤', special: false }
])

// 获取用户信息
const fetchUserInfo = () => {
  const userData = localStorage.getItem('user')
  if (userData) {
    user.value = JSON.parse(userData)
  }
}

// 获取用户标签
const fetchUserTags = async () => {
  try {
    const response = await userAPI.getUserTags()
    if (response.data.code === 0) {
      userTags.value = response.data.data || []
    }
  } catch (error) {
    console.error('获取用户标签失败:', error)
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      router.push('/login')
    }
  }
}

// 加载推荐内容
const loadRecommendations = async (page = 1, append = false) => {
  try {
    if (page === 1) {
      loading.value = true
    } else {
      loadingMore.value = true
    }

    // 构建请求参数
    const params = {
      page: page,
      size: pageSize.value,
      use_cache: false  // 禁用缓存，确保实时更新
    }
    
    // 如果有选择频道，添加频道过滤
    if (activeChannel.value && activeChannel.value.id) {
      params.tag_id = activeChannel.value.id
    }
    
    const response = await recommendationAPI.getRecommendations(params)

    if (response.data.success) {
      const newRecommendations = response.data.data?.recommendations || []
      
      if (append) {
        recommendations.value.push(...newRecommendations)
      } else {
        recommendations.value = newRecommendations
      }

      hasMore.value = newRecommendations.length === pageSize.value
      currentPage.value = page
      
      console.log(`加载第${page}页推荐内容（频道：${activeChannel.value?.name || '全部'}），共${newRecommendations.length}条`)
    } else {
      console.error('获取推荐内容失败:', response.data.message)
    }
  } catch (error) {
    console.error('获取推荐内容失败:', error)
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      router.push('/login')
    }
  } finally {
    loading.value = false
    loadingMore.value = false
  }
}

// 加载更多
const loadMore = () => {
  if (!loadingMore.value && hasMore.value) {
    loadRecommendations(currentPage.value + 1, true)
  }
}

// 切换标签
const switchTab = (tab) => {
  activeTab.value = tab
  if (tab === 'recommend' && recommendations.value.length === 0) {
    loadRecommendations()
  }
}

// 切换底部导航
const switchBottomTab = (tab) => {
  if (tab === 'publish') {
    // 跳转到发布页面
    router.push('/publish')
    return
  } else if (tab === 'my-content') {
    // 跳转到我的内容页面
    router.push('/my-content')
    return
  } else if (tab === 'profile') {
    // 跳转到个人主页（待开发）
    console.log('个人主页功能开发中')
    return
  } else if (tab === 'shopping') {
    // 购物功能（待开发）
    alert('购物功能开发中')
    return
  } else {
    // 其他标签
    activeBottomTab.value = tab
  }
}

// 处理内容查看 - 跳转到详情页
const handleContentView = async (content) => {
  try {
    // 记录查看行为
    await recommendationAPI.recordBehavior(content.content_id, 'view')
    
    // 跳转到详情页
    router.push(`/content/${content.content_id}`)
  } catch (error) {
    console.error('跳转失败:', error)
  }
}

// 处理内容点赞
const handleContentLike = async (content) => {
  try {
    await recommendationAPI.recordBehavior(content.content_id, 'like')
  } catch (error) {
    console.error('记录点赞行为失败:', error)
  }
}

// 处理内容分享
const handleContentShare = async (content) => {
  try {
    await recommendationAPI.recordBehavior(content.content_id, 'share')
  } catch (error) {
    console.error('记录分享行为失败:', error)
  }
}

// 处理搜索
const handleSearch = () => {
  console.log('搜索:', searchQuery.value)
  showSearch.value = false
}

// 无限滚动
let scrollHandler = null
const setupInfiniteScroll = () => {
  scrollHandler = () => {
    const scrollTop = window.pageYOffset || document.documentElement.scrollTop
    const windowHeight = window.innerHeight
    const documentHeight = document.documentElement.scrollHeight

    if (scrollTop + windowHeight >= documentHeight - 100) {
      loadMore()
    }
  }
  
  window.addEventListener('scroll', scrollHandler)
}

const removeInfiniteScroll = () => {
  if (scrollHandler) {
    window.removeEventListener('scroll', scrollHandler)
  }
}

// 监听频道变化
watch(activeChannel, () => {
  if (activeChannel.value) {
    recommendations.value = []
    currentPage.value = 1
    hasMore.value = true
    loadRecommendations()
  }
})

// 组件挂载
onMounted(async () => {
  fetchUserInfo()
  await fetchUserTags()
  
  // 加载用户频道
  await loadMyChannels()
  
  // 如果用户没有选择标签，跳转到兴趣选择页
  if (userTags.value.length === 0 && myChannels.value.length === 0) {
    router.push('/interest')
    return
  }
  
  // 加载推荐内容
  await loadRecommendations()
  
  // 设置无限滚动
  await nextTick()
  setupInfiniteScroll()
})

// 组件卸载
onUnmounted(() => {
  removeInfiniteScroll()
})
</script>

<style scoped>
/* 全局重置 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html, body {
  overflow-x: hidden;
  width: 100%;
}

.home {
  width: 100%;
  min-height: 100vh;
  background: #ffffff;
  position: relative;
  overflow-x: hidden;
  margin: 0;
  padding: 0;
}

/* 顶部导航栏 */
.top-nav {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 60px;
  background: #fff;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  align-items: center;
  padding: 0 16px;
  z-index: 1000;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.nav-left {
  flex: 0 0 auto;
}

.logo {
  display: flex;
  align-items: center;
  gap: 8px;
}

.logo-icon {
  font-size: 24px;
  color: #ff2442;
}

.logo-text {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.nav-center {
  flex: 1;
  display: flex;
  justify-content: center;
}

.nav-tabs {
  display: flex;
  gap: 32px;
}

.nav-tab {
  background: none;
  border: none;
  font-size: 16px;
  font-weight: 500;
  color: #666;
  cursor: pointer;
  padding: 8px 0;
  position: relative;
  transition: color 0.3s ease;
}

.nav-tab.active {
  color: #ff2442;
}

.nav-tab.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 2px;
  background: #ff2442;
  border-radius: 1px;
}

.nav-right {
  flex: 0 0 auto;
}

.search-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  padding: 8px;
  border-radius: 50%;
  transition: background-color 0.3s ease;
}

.search-btn:hover {
  background: #f0f7ff;
}

/* 分类标签栏 */
.category-bar {
  position: fixed;
  top: 60px;
  left: 0;
  width: 100%;
  height: 48px;
  background: #fff;
  border-bottom: 1px solid #e9ecef;
  z-index: 999;
  overflow-x: auto;
  overflow-y: hidden;
}

.category-scroll {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  white-space: nowrap;
  height: 100%;
}

.category-tag {
  flex-shrink: 0;
  padding: 6px 16px;
  border: none;
  background: #f8f8f8;
  color: #666;
  border-radius: 16px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
  white-space: nowrap;
}

.category-tag:hover {
  background: #f0f0f0;
}

.category-tag.active {
  background: #fff0f6;
  color: #ff2442;
}

.category-manage {
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 6px 12px;
  border: none;
  background: #f8f8f8;
  color: #666;
  border-radius: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.category-manage:hover {
  background: #e9ecef;
  color: #333;
}

.category-manage svg {
  width: 16px;
  height: 16px;
}

/* 内容区域 */
.content-area {
  margin-top: 108px;
  width: 100%;
  min-height: calc(100vh - 108px - 64px);
  background: #ffffff;
  padding-bottom: 64px;
}

/* 推荐内容 */
.recommend-content {
  width: 100%;
  padding: 0;
}

/* 空内容状态 */
.empty-content {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 60vh;
}

.empty-text {
  font-size: 16px;
  color: #999;
}

.content-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
  width: 100%;
  padding: 16px;
}

/* 响应式设计 */
@media (max-width: 640px) {
  .content-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 8px;
    padding: 8px;
  }
  
  .nav-tabs {
    gap: 16px;
  }
}

@media (min-width: 641px) and (max-width: 1024px) {
  .content-grid {
    grid-template-columns: repeat(3, 1fr);
    gap: 12px;
    padding: 12px;
  }
}

@media (min-width: 1025px) and (max-width: 1440px) {
  .content-grid {
    grid-template-columns: repeat(4, 1fr);
    gap: 16px;
    padding: 16px;
  }
}

@media (min-width: 1441px) {
  .content-grid {
    grid-template-columns: repeat(5, 1fr);
    gap: 20px;
    padding: 20px;
  }
}

/* 加载状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #666;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #ff2442;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

.loading-spinner.small {
  width: 20px;
  height: 20px;
  border-width: 2px;
  margin-bottom: 0;
  margin-right: 8px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 本地内容 */
.local-content {
  width: 100vw;
  padding: 20px;
  min-height: calc(100vh - 140px);
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  text-align: center;
  color: #666;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  max-width: 400px;
  width: 100%;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 16px;
  opacity: 0.6;
}

.empty-state h3 {
  font-size: 20px;
  margin-bottom: 8px;
  color: #333;
}

.empty-state p {
  font-size: 14px;
  margin-bottom: 24px;
  opacity: 0.8;
}

.refresh-btn {
  background: #ff2442;
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.refresh-btn:hover {
  background: #e01e3c;
  transform: translateY(-1px);
}

/* 加载更多 */
.load-more {
  display: flex;
  justify-content: center;
  padding: 32px 0;
}

.load-more-btn {
  background: #fff;
  color: #ff2442;
  border: 1px solid #ff2442;
  padding: 12px 32px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
}

.load-more-btn:hover:not(:disabled) {
  background: #ff2442;
  color: white;
}

.load-more-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 底部导航栏 */
.bottom-nav {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 64px;
  background: #fff;
  border-top: 1px solid #e9ecef;
  display: flex;
  align-items: center;
  justify-content: space-around;
  padding: 0;
  z-index: 1000;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
}

.nav-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: none;
  border: none;
  cursor: pointer;
  padding: 8px;
  position: relative;
  transition: all 0.3s ease;
}

.nav-item.special {
  background: #1890ff;
  border-radius: 50%;
  width: 48px;
  height: 48px;
  margin: 0;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.3);
  padding: 0;
}

.nav-item.special .nav-icon {
  font-size: 20px;
  color: white;
  margin: 0;
}

.nav-item.special .nav-label {
  position: absolute;
  bottom: -16px;
  font-size: 11px;
  color: #666;
  display: block;
  white-space: nowrap;
}

.nav-icon {
  font-size: 20px;
  margin: 0;
  transition: all 0.3s ease;
}

.nav-label {
  font-size: 11px;
  color: #666;
  font-weight: 400;
  transition: color 0.3s ease;
  margin-top: 4px;
}

.nav-item.active .nav-icon,
.nav-item.active .nav-label {
  color: #ff2442;
}

.nav-item.special.active .nav-icon {
  color: white;
}

.nav-item.special.active .nav-label {
  color: #1890ff;
}

.nav-badge {
  position: absolute;
  top: 4px;
  right: 50%;
  transform: translateX(50%);
  background: #ff2442;
  color: white;
  font-size: 10px;
  padding: 2px 6px;
  border-radius: 10px;
  min-width: 16px;
  text-align: center;
}

/* 搜索弹窗 */
.search-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: flex-start;
  justify-content: center;
  z-index: 2000;
  padding-top: 80px;
}

.search-content {
  background: white;
  border-radius: 12px;
  width: 90%;
  max-width: 500px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
}

.search-header {
  display: flex;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #e9ecef;
}

.search-input {
  flex: 1;
  border: none;
  outline: none;
  font-size: 16px;
  padding: 8px 12px;
  background: #f5f5f5;
  border-radius: 20px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  color: #666;
  cursor: pointer;
  padding: 8px;
  margin-left: 8px;
}

.search-suggestions {
  padding: 20px;
  text-align: center;
  color: #666;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .content-grid {
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 12px;
  }
  
  .nav-tabs {
    gap: 24px;
  }
  
  .nav-tab {
    font-size: 14px;
  }
  
  .content-area {
    padding: 12px;
  }
}

@media (max-width: 480px) {
  .content-grid {
    grid-template-columns: 1fr;
    gap: 8px;
  }
  
  .nav-tabs {
    gap: 16px;
  }
  
  .nav-tab {
    font-size: 13px;
  }
  
  .logo-text {
    font-size: 16px;
  }
  
  .top-nav {
    padding: 0 12px;
  }
  
  .content-area {
    padding: 8px;
  }
}
</style>